package com.soft.small.host.udp;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.*;

@Slf4j
public class UDPServer {
    public void start(String sn)  {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(20005);
            byte[] buf1 = new byte[1024];
            DatagramPacket dpr = new DatagramPacket(buf1, buf1.length);
            while (true){
                //接收数据
                socket.receive(dpr);
                String clientIp = dpr.getAddress().getHostAddress();
                log.info("发送的客户端IP是：{}", clientIp);
                int clientPort = dpr.getPort();
                log.info("发送的客户端port是：{}", clientPort);
                String text = new String(dpr.getData(), 0, dpr.getLength());
                log.info("客户端发送的协议是：{}", text);

                String sendMsg = "{\"si\": \""+sn+"\", \"oemFire\": \"0X8001\", \"activeState\": 0 }";
                log.info("主机返回的协议内容：{}",sendMsg);
                byte[] buf2 = sendMsg.getBytes();
                DatagramPacket dps = new DatagramPacket(buf2, buf2.length, InetAddress.getByName(clientIp), clientPort);
                socket.send(dps);
            }
        }catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket == null){
                socket.close();
                socket.disconnect();
            }
        }


        //socket.close();
    }

    public static void main(String[] args) throws IOException {
        new UDPServer().start("2041g22c36eb443a9de69bde4b76e464");
    }
}
